<template>
  <view class="page-container">
    <!-- 功能切换标签 -->
    <view class="tab-container">
      <view 
        v-for="tab in tabs" 
        :key="tab.key"
        class="tab-item"
        :class="{ active: currentTab === tab.key }"
        @click="switchTab(tab.key)"
      >
        <text class="tab-text">{{ tab.text }}</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content-area" :scroll-y="true" :style="{ height: scrollHeight }">

    <!-- 个人排班查看 -->
    <view v-if="currentTab === 'personal'" class="personal-schedule">
      <!-- 日期选择器 -->
      <view class="date-picker-section">
        <u-calendar
          v-model="selectedDate"
          :min-date="minDate"
          :max-date="maxDate"
          @change="handleDateChange"
          mode="date"
          :show-today="true"
        ></u-calendar>
      </view>

      <!-- 今日排班信息 -->
      <view class="today-schedule-card">
        <view class="card-header">
          <text class="card-title">今日排班</text>
          <text class="card-date">{{ formatDate(selectedDate) }}</text>
        </view>
        
        <view v-if="todaySchedule" class="schedule-content">
          <view class="schedule-item">
            <view class="schedule-icon">
              <u-icon name="clock" color="#fff" size="18"></u-icon>
            </view>
            <view class="schedule-info">
              <text class="schedule-label">班次类型</text>
              <text class="schedule-value">{{ todaySchedule.shiftType }}</text>
            </view>
          </view>
          
          <view class="schedule-item">
            <view class="schedule-icon">
              <u-icon name="time" color="#fff" size="18"></u-icon>
            </view>
            <view class="schedule-info">
              <text class="schedule-label">工作时间</text>
              <text class="schedule-value">{{ todaySchedule.startTime }} - {{ todaySchedule.endTime }}</text>
            </view>
          </view>
          
          <view class="schedule-item">
            <view class="schedule-icon">
              <u-icon name="map-marker" color="#fff" size="18"></u-icon>
            </view>
            <view class="schedule-info">
              <text class="schedule-label">工作区域</text>
              <text class="schedule-value">{{ todaySchedule.workArea }}</text>
            </view>
          </view>
        </view>
        
        <view v-else class="no-schedule">
          <u-icon name="calendar" color="#ccc" size="40"></u-icon>
          <text class="no-schedule-text">今日无排班安排</text>
        </view>
      </view>

      <!-- 本周排班概览 -->
      <view class="week-schedule-card">
        <view class="card-header">
          <text class="card-title">本周排班</text>
          <text class="card-subtitle">{{ getWeekRange() }}</text>
        </view>
        
        <view class="week-schedule-list">
          <view 
            v-for="schedule in weekSchedules" 
            :key="schedule.date"
            class="week-schedule-item"
            :class="{ today: schedule.isToday }"
          >
            <view class="schedule-date">
              <text class="date-text">{{ schedule.dayOfWeek }}</text>
              <text class="date-number">{{ schedule.dayNumber }}</text>
            </view>
            <view class="schedule-details">
              <text class="shift-type">{{ schedule.shiftType || '休息' }}</text>
              <text class="work-time">{{ schedule.workTime || '' }}</text>
            </view>
            <view class="schedule-status">
              <u-tag 
                :text="schedule.status" 
                :type="schedule.statusType" 
                size="mini"
              ></u-tag>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 部门排班管理 -->
    <view v-if="currentTab === 'department'" class="department-schedule">
      <!-- 管理功能按钮 -->
      <view class="management-actions">
        <u-button 
          type="primary" 
          text="创建排班" 
          icon="plus"
          @click="createSchedule"
        ></u-button>
        <u-button 
          type="success" 
          text="批量排班" 
          icon="calendar"
          @click="batchSchedule"
        ></u-button>
        <u-button 
          type="info" 
          text="导入排班" 
          icon="upload"
          @click="importSchedule"
        ></u-button>
      </view>

      <!-- 部门人员排班表 -->
      <view class="schedule-table-card">
        <view class="card-header">
          <text class="card-title">部门排班表</text>
          <view class="date-navigation">
            <u-button 
              type="text" 
              text="上周" 
              icon="arrow-left"
              @click="previousWeek"
            ></u-button>
            <text class="current-week">{{ getCurrentWeekRange() }}</text>
            <u-button 
              type="text" 
              text="下周" 
              icon="arrow-right"
              @click="nextWeek"
            ></u-button>
          </view>
        </view>
        
        <view class="schedule-table">
          <view class="table-header">
            <view class="header-cell name">姓名</view>
            <view class="header-cell" v-for="day in weekDays" :key="day">
              {{ day }}
            </view>
          </view>
          
          <view 
            v-for="staff in departmentStaff" 
            :key="staff.id"
            class="table-row"
          >
            <view class="staff-cell">
              <text class="staff-name">{{ staff.name }}</text>
              <text class="staff-role">{{ staff.role }}</text>
            </view>
            <view 
              v-for="day in weekDays" 
              :key="day"
              class="schedule-cell"
              @click="editStaffSchedule(staff, day)"
            >
              <view v-if="staff.schedules[day]" class="schedule-info">
                <text class="shift-type">{{ staff.schedules[day].shiftType }}</text>
                <text class="work-time">{{ staff.schedules[day].workTime }}</text>
              </view>
              <view v-else class="no-schedule">
                <text class="no-schedule-text">-</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 调班申请 -->
    <view v-if="currentTab === 'change'" class="change-request">
      <!-- 我的调班申请 -->
      <view class="my-requests-card">
        <view class="card-header">
          <text class="card-title">我的调班申请</text>
          <u-button 
            type="primary" 
            text="申请调班" 
            size="small"
            @click="createChangeRequest"
          ></u-button>
        </view>
        
        <view class="request-list">
          <view 
            v-for="request in myChangeRequests" 
            :key="request.id"
            class="request-item"
            @click="viewRequestDetail(request)"
          >
            <view class="request-info">
              <text class="request-date">{{ request.originalDate }} → {{ request.targetDate }}</text>
              <text class="request-reason">{{ request.reason }}</text>
            </view>
            <view class="request-status">
              <u-tag 
                :text="request.statusText" 
                :type="request.statusType" 
                size="small"
              ></u-tag>
            </view>
          </view>
        </view>
      </view>

      <!-- 待我确认的调班申请 -->
      <view v-if="isManager" class="pending-requests-card">
        <view class="card-header">
          <text class="card-title">待我确认的调班申请</text>
          <u-badge :count="pendingRequestsCount" type="error"></u-badge>
        </view>
        
        <view class="request-list">
          <view 
            v-for="request in pendingRequests" 
            :key="request.id"
            class="request-item"
            @click="viewRequestDetail(request)"
          >
            <view class="request-info">
              <text class="request-applicant">{{ request.applicantName }}</text>
              <text class="request-date">{{ request.originalDate }} → {{ request.targetDate }}</text>
            </view>
            <view class="request-actions">
              <u-button 
                type="success" 
                text="同意" 
                size="mini"
                @click="approveRequest(request)"
              ></u-button>
              <u-button 
                type="error" 
                text="拒绝" 
                size="mini"
                @click="rejectRequest(request)"
              ></u-button>
            </view>
          </view>
        </view>
      </view>
    </view>
    </scroll-view>
  </view>
</template>

<script setup>
/**
 * 排班管理页面
 * @author Wu.Liang
 * @date 2025-01-30
 * @version 1.0.0
 */

import { ref, reactive, computed, onMounted } from 'vue'

// 页面高度计算
const scrollHeight = ref('calc(100vh - 200px)')

// 计算滚动视图高度
const calculateScrollHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync()
    const windowHeight = systemInfo.windowHeight
    const statusBarHeight = systemInfo.statusBarHeight || 0
    const navbarHeight = 44 // 导航栏内容高度
    const tabsHeight = 44 // 标签页高度
    const padding = 16 // 上下边距
    
    // 计算实际可用高度（去除自定义头部后，只需要减去系统导航栏和标签页高度）
    const calculatedHeight = windowHeight - statusBarHeight - navbarHeight - tabsHeight - padding
    
    return `${calculatedHeight}px`
  } catch (error) {
    console.error('计算高度失败:', error)
    return 'calc(100vh - 120px)'
  }
}

// 响应式数据
const currentTab = ref('personal')
const selectedDate = ref(new Date())
const minDate = ref(new Date(2024, 0, 1))
const maxDate = ref(new Date(2025, 11, 31))

// 标签页配置
const tabs = ref([
  { key: 'personal', text: '我的排班' },
  { key: 'department', text: '部门排班' },
  { key: 'change', text: '调班申请' }
])

// 今日排班数据
const todaySchedule = ref({
  shiftType: '早班',
  startTime: '08:00',
  endTime: '16:00',
  workArea: 'A栋1-10层'
})

// 本周排班数据
const weekSchedules = ref([
  { date: '2025-01-27', dayOfWeek: '周一', dayNumber: '27', shiftType: '早班', workTime: '08:00-16:00', status: '已完成', statusType: 'success', isToday: false },
  { date: '2025-01-28', dayOfWeek: '周二', dayNumber: '28', shiftType: '晚班', workTime: '16:00-24:00', status: '已完成', statusType: 'success', isToday: false },
  { date: '2025-01-29', dayOfWeek: '周三', dayNumber: '29', shiftType: '早班', workTime: '08:00-16:00', status: '进行中', statusType: 'warning', isToday: true },
  { date: '2025-01-30', dayOfWeek: '周四', dayNumber: '30', shiftType: '休息', workTime: '', status: '待开始', statusType: 'info', isToday: false },
  { date: '2025-01-31', dayOfWeek: '周五', dayNumber: '31', shiftType: '早班', workTime: '08:00-16:00', status: '待开始', statusType: 'info', isToday: false },
  { date: '2025-02-01', dayOfWeek: '周六', dayNumber: '01', shiftType: '休息', workTime: '', status: '待开始', statusType: 'info', isToday: false },
  { date: '2025-02-02', dayOfWeek: '周日', dayNumber: '02', shiftType: '休息', workTime: '', status: '待开始', statusType: 'info', isToday: false }
])

// 部门排班数据
const weekDays = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日'])
const departmentStaff = ref([
  {
    id: 1,
    name: '张三',
    role: '保洁员',
    schedules: {
      '周一': { shiftType: '早班', workTime: '08:00-16:00' },
      '周二': { shiftType: '晚班', workTime: '16:00-24:00' },
      '周三': { shiftType: '早班', workTime: '08:00-16:00' },
      '周四': null,
      '周五': { shiftType: '早班', workTime: '08:00-16:00' },
      '周六': null,
      '周日': null
    }
  },
  {
    id: 2,
    name: '李四',
    role: '保洁员',
    schedules: {
      '周一': null,
      '周二': { shiftType: '早班', workTime: '08:00-16:00' },
      '周三': { shiftType: '晚班', workTime: '16:00-24:00' },
      '周四': { shiftType: '早班', workTime: '08:00-16:00' },
      '周五': null,
      '周六': { shiftType: '早班', workTime: '08:00-16:00' },
      '周日': null
    }
  }
])

// 调班申请数据
const myChangeRequests = ref([
  {
    id: 1,
    originalDate: '2025-01-30',
    targetDate: '2025-02-01',
    reason: '家中有事需要调班',
    statusText: '待审批',
    statusType: 'warning'
  }
])

const pendingRequests = ref([
  {
    id: 2,
    applicantName: '王五',
    originalDate: '2025-01-31',
    targetDate: '2025-02-02',
    reason: '个人原因需要调班'
  }
])

const pendingRequestsCount = computed(() => pendingRequests.value.length)
const isManager = ref(true) // 根据用户权限判断

// 方法

const switchTab = (tabKey) => {
  currentTab.value = tabKey
}

const handleDateChange = (date) => {
  selectedDate.value = date
  // 根据日期加载排班数据
  loadScheduleData(date)
}

const formatDate = (date) => {
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

const getWeekRange = () => {
  const today = new Date()
  const startOfWeek = new Date(today.setDate(today.getDate() - today.getDay() + 1))
  const endOfWeek = new Date(today.setDate(today.getDate() - today.getDay() + 7))
  return `${formatDate(startOfWeek)} - ${formatDate(endOfWeek)}`
}

const getCurrentWeekRange = () => {
  return getWeekRange()
}

const loadScheduleData = (date) => {
  // 根据日期加载排班数据
  console.log('加载日期排班数据:', date)
}

const createSchedule = () => {
  uni.navigateTo({ url: '/pages/property-work/schedule-create' })
}

const batchSchedule = () => {
  uni.navigateTo({ url: '/pages/property-work/schedule-batch' })
}

const importSchedule = () => {
  uni.chooseFile({
    count: 1,
    type: 'file',
    success: (res) => {
      console.log('选择文件:', res)
    }
  })
}

const previousWeek = () => {
  // 切换到上一周
  console.log('切换到上一周')
}

const nextWeek = () => {
  // 切换到下一周
  console.log('切换到下一周')
}

const editStaffSchedule = (staff, day) => {
  uni.navigateTo({ 
    url: `/pages/property-work/schedule-edit?staffId=${staff.id}&day=${day}` 
  })
}

const createChangeRequest = () => {
  uni.navigateTo({ url: '/pages/property-work/schedule-change-request' })
}

const viewRequestDetail = (request) => {
  uni.navigateTo({ 
    url: `/pages/property-work/schedule-change-detail?id=${request.id}` 
  })
}

const approveRequest = (request) => {
  uni.showModal({
    title: '确认审批',
    content: '确定同意这个调班申请吗？',
    success: (res) => {
      if (res.confirm) {
        // 处理审批逻辑
        console.log('同意调班申请:', request.id)
      }
    }
  })
}

const rejectRequest = (request) => {
  uni.showModal({
    title: '确认拒绝',
    content: '确定拒绝这个调班申请吗？',
    success: (res) => {
      if (res.confirm) {
        // 处理拒绝逻辑
        console.log('拒绝调班申请:', request.id)
      }
    }
  })
}

onMounted(() => {
  // 计算页面高度
  scrollHeight.value = calculateScrollHeight()
  
  // 页面加载时初始化数据
  loadScheduleData(selectedDate.value)
})
</script>

<style scoped>
/* 页面容器规范 */
.page-container {
  min-height: 100vh;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 内容区域规范 */
.content-area {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  padding: 16px;
}


.tab-container {
  display: flex;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  flex: 1;
  padding: 30rpx 0;
  text-align: center;
  border-bottom: 4rpx solid transparent;
}

.tab-item.active {
  border-bottom-color: #667eea;
}

.tab-text {
  font-size: 28rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #667eea;
  font-weight: bold;
}

.personal-schedule,
.department-schedule,
.change-request {
  padding: 30rpx;
}

.date-picker-section {
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  padding: 30rpx;
}

.today-schedule-card,
.week-schedule-card,
.schedule-table-card,
.my-requests-card,
.pending-requests-card {
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  padding: 30rpx;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.card-date,
.card-subtitle {
  font-size: 24rpx;
  color: #999;
}

.schedule-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.schedule-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.schedule-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #667eea;
  display: flex;
  align-items: center;
  justify-content: center;
}

.schedule-info {
  flex: 1;
}

.schedule-label {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 8rpx;
}

.schedule-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.no-schedule {
  text-align: center;
  padding: 60rpx 0;
}

.no-schedule-text {
  font-size: 28rpx;
  color: #ccc;
  margin-top: 20rpx;
}

.week-schedule-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.week-schedule-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 16rpx;
}

.week-schedule-item.today {
  background-color: #e3f2fd;
  border: 2rpx solid #2196f3;
}

.schedule-date {
  width: 120rpx;
  text-align: center;
}

.date-text {
  font-size: 24rpx;
  color: #666;
  display: block;
}

.date-number {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  display: block;
}

.schedule-details {
  flex: 1;
  margin-left: 20rpx;
}

.shift-type {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
}

.work-time {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-top: 8rpx;
}

.schedule-status {
  margin-left: 20rpx;
}

.management-actions {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.date-navigation {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.current-week {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.schedule-table {
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  overflow: hidden;
}

.table-header {
  display: flex;
  background-color: #f8f9fa;
}

.header-cell {
  flex: 1;
  padding: 20rpx;
  text-align: center;
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
  border-right: 1rpx solid #eee;
}

.header-cell.name {
  flex: 0 0 120rpx;
}

.table-row {
  display: flex;
  border-bottom: 1rpx solid #eee;
}

.staff-cell {
  flex: 0 0 120rpx;
  padding: 20rpx;
  border-right: 1rpx solid #eee;
  background-color: #f8f9fa;
}

.staff-name {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  display: block;
}

.staff-role {
  font-size: 22rpx;
  color: #666;
  display: block;
  margin-top: 8rpx;
}

.schedule-cell {
  flex: 1;
  padding: 20rpx;
  text-align: center;
  border-right: 1rpx solid #eee;
  min-height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.schedule-info {
  text-align: center;
}

.shift-type {
  font-size: 24rpx;
  color: #333;
  display: block;
}

.work-time {
  font-size: 20rpx;
  color: #666;
  display: block;
  margin-top: 4rpx;
}

.no-schedule-text {
  font-size: 24rpx;
  color: #ccc;
}

.request-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.request-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
}

.request-info {
  flex: 1;
}

.request-date {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
}

.request-reason,
.request-applicant {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-top: 8rpx;
}

.request-status {
  margin-left: 20rpx;
}

.request-actions {
  display: flex;
  gap: 10rpx;
  margin-left: 20rpx;
}
</style>
